<template>
  <div class="w-full flex flex-col gap-4">
    <guat-button-group
      :buttons="[
        { text: expandAll ? '全部折叠' : '全部展开', onClick: handleExpand },
        { text: checkedAll ? '取消全选' : '全选', onClick: handleCheckAll },
      ]"
    />
    <div class="w-full p-1 rounded border border-solid border-bc-2">
      <a-scrollbar :style="{ height: '320px', overflow: 'auto' }">
        <a-tree
          checkable
          :data="permissions"
          :defaultExpandAll="expandAll"
          v-model:checkedKeys="checkedKeys"
          v-model:expandedKeys="expandKeys"
        />
      </a-scrollbar>
    </div>
  </div>
</template>

<script setup lang="ts">
import { TreeNodeData } from "@arco-design/web-vue";
import { permissions } from "../tree-data";

const checkedKeys = defineModel<any[]>("checkedKeys");

const expandKeys = ref<(string | number)[]>([]);
const expandAll = computed(() => !!expandKeys.value.length);
const expandableKeys = getExpandableKeys(permissions);

const allKeys = getAllKeys(permissions);
const checkedAll = computed(() => checkedKeys.value?.length == allKeys.length);

const handleExpand = () => {
  expandKeys.value = !unref(expandKeys).length ? expandableKeys : [];
};

const handleCheckAll = () => {
  checkedKeys.value = !checkedKeys.value?.length ? allKeys : [];
};

function getExpandableKeys(permissions: TreeNodeData[]) {
  let keys: (string | number)[] = [];
  permissions.forEach((permission) => {
    if (permission.children) {
      keys.push(permission.key!);
      const childKeys = getExpandableKeys(permission.children);
      keys = keys.concat(childKeys);
    }
  });
  return keys;
}

function getAllKeys(permissions: TreeNodeData[]) {
  let keys: (string | number)[] = [];
  permissions.forEach((permissions) => {
    keys.push(permissions.key!);
    if (permissions.children) {
      const childKeys = getAllKeys(permissions.children);
      keys = keys.concat(childKeys);
    }
  });
  return keys;
}
</script>

<style scoped></style>
